package net.yla.smartbus.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;

/**
 * @author Handy Wong
 * @date 2020/1/13 12:00
 * 获取原生jdbc
 */
@Component
public class SqlConnection {
    @Value(value = "${spring.datasource.url}")
    private String dataUrl;
    @Value(value = "${spring.datasource.username}")
    private String dataUserName;
    @Value(value = "${spring.datasource.password}")
    private String dataPassWord;
    @Value(value = "${spring.datasource.driver-class-name}")
    private String dataDriver;
    private static String url;
    private static String userName;
    private static String passWord;
    private static String driver;
    private static final Logger logger = LoggerFactory.getLogger(SqlConnection.class);
    @Autowired
    public void setUrl() {
        SqlConnection.url = this.dataUrl;
    }

    @Autowired
    public void setUserName() {
        SqlConnection.userName = this.dataUserName;
    }

    @Autowired
    public void setPassWord() {
        SqlConnection.passWord = this.dataPassWord;
    }

    @Autowired
    public void setDriver() {
        SqlConnection.driver = this.dataDriver;
    }

    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, passWord);
            logger.info("Connection:"+conn);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeConn(Connection conn) {
        if (null != conn) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static PreparedStatement getPstm(Connection conn, String sql) {
        PreparedStatement preparedStatement = null;
        try {
                preparedStatement = conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        logger.info("PreparedStatement:"+preparedStatement);
        return preparedStatement;
    }

    public static void closePstm(PreparedStatement preparedStatement) {
        if (null != preparedStatement) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public static void closeResult(ResultSet set){
        if(null!=set){
            try {
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
